package com.googlecode.economini.converter;

import org.xml.sax.Attributes;

public class TokenFactories {

  private TokenFactories() { /* Do not instantiate */ }

  public static <T extends Enum<?>> TokenFactory<T> valueTokenFacotry(
      final T type) {
    return new TokenFactory<T>() {
      @Override
      public Token<T> fromElement(String element, Attributes attributes) {
        if (element == null) {
          return null;
        }

        return new Token<T>(element, type);
      }
    };
  }

  public static <T extends Enum<?>> TokenFactory<T> attributeTokenFacotry(
      final String attribute, final T type) {
    return new TokenFactory<T>() {
      @Override
      public Token<T> fromElement(String element, Attributes attributes) {
        if (element != null) {
          return null;
        }

        String value = attributes.getValue(attribute);
        if (value == null) {
          return null;
        }
        return new Token<T>(value, type);
      }
    };
  }

  public static <T extends Enum<?>> TokenFactory<T> compoundTokenFacotry(
      final T elementType, final String attribute, final T attributeType) {
    return new TokenFactory<T>() {
      @Override
      public Token<T> fromElement(String element, Attributes attributes) {
        if (element != null) {
          return new Token<T>(element, elementType);
        }

        String value = attributes.getValue(attribute);
        if (value == null) { return null; }

        return new Token<T>(value, attributeType);
      }
    };
  }

  public static <T extends Enum<?>> TokenFactory<T> matchElement(
      final TokenFactory<T> tokenFactory, final String elementValue) {
    return new TokenFactory<T>() {
      @Override
      public Token<T> fromElement(String element, Attributes attributes) {
        if (!elementValue.equals(element)) {
          return null;
        }

        return tokenFactory.fromElement(elementValue, attributes);
      }
    };
  }
}
